<template>
  <div class="department-manage">
    <el-card class="department-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">部门管理</span>
          <div class="search-box">
            <el-input
              v-model.trim="searchName"
              placeholder="请输入部门名称"
              clearable
              class="search-input"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" icon="Search" class="search-btn" @click="handleSearch">搜索</el-button>
            <el-button icon="Refresh" class="reset-btn" @click="handleReset">重置</el-button>
            <el-button type="success" icon="Plus" class="add-btn" @click="handleAdd">新增部门</el-button>
          </div>
        </div>
      </template>

      <!-- 部门列表 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        empty-text="暂无数据"
        class="department-table"
        :header-cell-style="{
          background: '#f8faff',
          color: '#303133',
          fontWeight: '600',
          fontSize: '14px'
        }"
      >
        <el-table-column prop="id" label="部门编号" width="100" />
        <el-table-column prop="name" label="部门名称" width="180" />
        <el-table-column prop="code" label="部门编码" width="120" />
        <el-table-column prop="employeeCount" label="成员数量" width="100">
          <template #default="scope">
            {{ scope.row.employeeCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'danger' : 'success'" effect="light">
              {{ scope.row.status === 1 ? '禁用' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ scope.row.createdTime || '暂无' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="部门描述" min-width="180">
          <template #default="scope">
            {{ scope.row.description || '暂无描述' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click="handleViewMembers(scope.row)"
              class="action-btn"
            >
              查看成员
            </el-button>
            <el-button 
              link 
              type="primary" 
              @click="handleEdit(scope.row)"
              class="action-btn"
            >
              编辑
            </el-button>
            <el-button 
              link 
              type="danger" 
              @click="handleDelete(scope.row)"
              class="action-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>
    </el-card>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增部门' : '编辑部门'"
      width="500px"
      class="department-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" class="form-input" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入部门编码" class="form-input" />
        </el-form-item>
        <el-form-item label="上级部门">
          <el-input v-model="form.parentId" placeholder="上级部门ID，0表示顶级部门" class="form-input" />
        </el-form-item>
        <el-form-item label="部门状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            rows="3"
            placeholder="请输入部门描述"
            class="form-textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading" class="submit-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 部门成员对话框 -->
    <el-dialog
      v-model="memberDialogVisible"
      :title="currentDepartment ? `${currentDepartment.name}部门成员` : '部门成员'"
      width="900px"
      destroy-on-close
      class="member-dialog"
    >
      <div class="department-info" v-if="currentDepartment">
        <div class="info-item">
          <span class="label">部门编号:</span>
          <span class="value">{{ currentDepartment.id }}</span>
        </div>
        <div class="info-item">
          <span class="label">部门编码:</span>
          <span class="value">{{ currentDepartment.code }}</span>
        </div>
        <div class="info-item">
          <span class="label">成员数量:</span>
          <span class="value">{{ currentDepartment.employeeCount || memberList.length || 0 }}</span>
        </div>
        <div class="info-item">
          <span class="label">部门描述:</span>
          <span class="value">{{ currentDepartment.description || '无' }}</span>
        </div>
      </div>

      <el-divider />
      
      <el-table 
        :data="memberList" 
        border 
        style="width: 100%"
        v-loading="memberLoading"
        max-height="500"
        class="member-table"
        :header-cell-style="{
          background: '#f8faff',
          color: '#303133',
          fontWeight: '600',
          fontSize: '14px'
        }"
      >
        <el-table-column prop="employeeNo" label="工号" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="phoneNumber" label="联系电话" width="140" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="hireDate" label="入职日期" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'danger' : 'success'" effect="light">
              {{ scope.row.status === 1 ? '停用' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="memberDialogVisible = false" class="close-btn">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import departmentApi from '@/api/admin/Department'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const submitLoading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const currentDepartmentId = ref(null)
const form = reactive({
  name: '',
  manager: '',
  description: '',
  code: '', // 部门编码
  parentId: 0, // 父部门ID，默认为0表示顶级部门
  status: 0 // 部门状态
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入部门描述', trigger: 'blur' }
  ]
}

// 部门主管选项
const managerOptions = [
  { value: '张三', label: '张三' },
  { value: '李四', label: '李四' },
  { value: '王五', label: '王五' }
]

// 部门成员相关
const memberDialogVisible = ref(false)
const memberList = ref([])
const memberLoading = ref(false)
const currentDepartment = ref(null)

// 获取部门列表
const fetchDepartmentList = async () => {
  loading.value = true;
  try {
    // 修正参数名称，确保与后端API匹配
    const params = {
      // 'current'是页码，'size'是每页条数
      current: currentPage.value,
      size: pageSize.value
    };
    
    // 只有当搜索名称不为空时才添加到参数中
    if (searchName.value.trim()) {
      params.name = searchName.value.trim();
    }
    
    console.log('请求参数:', params);
    
    const res = await departmentApi.getDepartmentList(params);
    console.log('接口返回数据:', res);
    
    if (res && res.data) {
      // 判断返回数据的结构
      if (Array.isArray(res.data)) {
        // 如果直接返回数组，说明不是分页结构
        tableData.value = res.data;
        total.value = res.data.length;
      } else if (res.data.records) {
        // 标准分页结构
        tableData.value = res.data.records;
        total.value = res.data.total || 0;
        // 同步当前页和总页数
        if (res.data.current) currentPage.value = res.data.current;
      } else {
        // 其他情况，尝试直接使用data
        tableData.value = res.data || [];
        total.value = (res.data && res.data.length) || 0;
      }
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取部门列表出错:', error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 新增部门
const handleAdd = () => {
  dialogType.value = 'add'
  currentDepartmentId.value = null
  // 重置表单
  form.name = ''
  form.code = ''
  form.description = ''
  form.parentId = 0
  form.status = 0
  
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (row) => {
  dialogType.value = 'edit'
  currentDepartmentId.value = row.id
  
  console.log('编辑部门行数据:', row);
  
  // 填充表单
  form.name = row.name
  form.code = row.code || ''
  form.description = row.description || ''
  form.parentId = row.parentId || 0
  form.status = row.status
  
  dialogVisible.value = true
}

// 删除部门
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该部门吗？删除后不可恢复。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const res = await departmentApi.deleteDepartment(row.id);
    if (res) {
      ElMessage.success('删除成功');
      // 重新加载部门列表
      fetchDepartmentList();
    }
  }).catch(() => {});
};

// 查看部门成员
const handleViewMembers = async (row) => {
  memberLoading.value = true;
  memberList.value = [];
  currentDepartment.value = row;
  
  try {
    const res = await departmentApi.getDepartmentEmployees(row.id);
    if (res && res.data) {
      // 判断返回的数据格式
      if (res.data.records) {
        memberList.value = res.data.records;
      } else if (Array.isArray(res.data)) {
        memberList.value = res.data;
      }
      memberDialogVisible.value = true;
    }
  } finally {
    memberLoading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        let res = null;
        if (dialogType.value === 'add') {
          // 新增部门
          const createData = {
            name: form.name,
            code: form.code,
            description: form.description,
            parentId: form.parentId || 0,
            status: form.status || 0
          };
          res = await departmentApi.addDepartment(createData);
        } else {
          // 编辑部门
          const updateData = {
            id: currentDepartmentId.value,
            name: form.name,
            code: form.code,
            description: form.description,
            parentId: form.parentId || 0,
            status: form.status || 0
          };
          res = await departmentApi.editDepartment(updateData);
        }
        
        if (res) {
          ElMessage.success(dialogType.value === 'add' ? '新增成功' : '修改成功');
          dialogVisible.value = false;
          // 重新加载部门列表
          fetchDepartmentList();
        }
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  // 修改每页条数后可能需要重置页码，避免无数据
  if (Math.ceil(total.value / val) < currentPage.value) {
    currentPage.value = 1;
  }
  fetchDepartmentList();
}

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchDepartmentList();
}

// 搜索相关
const searchName = ref('')
const handleSearch = () => {
  // 搜索时重置为第一页
  currentPage.value = 1;
  fetchDepartmentList();
}
const handleReset = () => {
  searchName.value = '';
  currentPage.value = 1;
  fetchDepartmentList();
}

// 初始化加载数据
onMounted(() => {
  fetchDepartmentList()
})
</script>

<style scoped lang="scss">
.department-manage {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  
  .department-card {
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    overflow: hidden;
    
    &:hover {
      box-shadow: 0 12px 32px rgba(24, 144, 255, 0.1);
      transform: translateY(-2px);
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
    
    .header-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      position: relative;
      padding-left: 12px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 18px;
        background: #1890ff;
        border-radius: 2px;
      }
    }
    
    .search-box {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .search-input {
        width: 220px;
        
        :deep(.el-input__wrapper) {
          border-radius: 8px;
          box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
          
          &:hover, &.is-focus {
            box-shadow: 0 0 0 1px #1890ff inset;
          }
        }
      }
      
      .search-btn {
        background: linear-gradient(135deg, #1890ff, #36a6ff);
        border: none;
        border-radius: 20px;
        padding: 8px 16px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);
        
        &:hover {
          background: linear-gradient(135deg, #40a9ff, #5cbbff);
          box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
          transform: translateY(-2px);
        }
        
        &:active {
          background: linear-gradient(135deg, #096dd9, #1890ff);
          transform: translateY(0);
        }
      }
      
      .reset-btn {
        background: #f5f7fa;
        color: #606266;
        border: none;
        border-radius: 20px;
        padding: 8px 16px;
        transition: all 0.3s ease;
        
        &:hover {
          background: #e6f7ff;
          color: #1890ff;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
          transform: translateY(-2px);
        }
        
        &:active {
          background: #dcf0fd;
          transform: translateY(0);
        }
      }
      
      .add-btn {
        background: linear-gradient(135deg, #52c41a, #72db3f);
        border: none;
        border-radius: 20px;
        padding: 8px 16px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 6px rgba(82, 196, 26, 0.2);
        
        &:hover {
          background: linear-gradient(135deg, #72db3f, #95eb64);
          box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
          transform: translateY(-2px);
        }
        
        &:active {
          background: linear-gradient(135deg, #389e0d, #52c41a);
          transform: translateY(0);
        }
      }
    }
  }
  
  .department-table {
    margin: 16px 0;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    
    :deep(.el-table__row) {
      transition: all 0.3s;
      
      &:hover {
        background-color: #f8faff !important;
      }
    }
    
    :deep(.el-table__cell) {
      padding: 10px 0;
    }
    
    :deep(.el-tag) {
      padding: 0 10px;
      height: 28px;
      line-height: 28px;
      border-radius: 4px;
      font-weight: 500;
      font-size: 12px;
      
      &.el-tag--success {
        background-color: rgba(82, 196, 26, 0.08);
        border-color: rgba(82, 196, 26, 0.2);
        color: #52c41a;
      }
      
      &.el-tag--danger {
        background-color: rgba(245, 34, 45, 0.08);
        border-color: rgba(245, 34, 45, 0.2);
        color: #f5222d;
      }
    }
    
    .action-btn {
      font-size: 13px;
      font-weight: 500;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        opacity: 0.8;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
    
    :deep(.custom-pagination) {
      padding: 0;
      
      .el-pagination__total {
        margin-right: 16px;
        color: #606266;
        font-weight: 500;
      }
      
      .el-pagination__sizes {
        margin-right: 16px;
        
        .el-select .el-input {
          width: 110px;
          
          .el-input__wrapper {
            background-color: #f5f7fa;
            border-radius: 20px;
          }
        }
      }
      
      button {
        background-color: #f5f7fa;
        border-radius: 4px;
        margin: 0 3px;
        color: #606266;
        transition: all 0.2s ease;
        
        &:hover {
          color: #1890ff;
          background-color: #e6f7ff;
        }
        
        &:disabled {
          color: #c0c4cc;
        }
      }
      
      .btn-prev, .btn-next {
        padding: 0 8px;
        
        &:hover {
          background-color: #e6f7ff;
        }
      }
      
      .el-pager {
        li {
          background-color: #f5f7fa;
          border-radius: 4px;
          margin: 0 3px;
          color: #606266;
          font-weight: 500;
          min-width: 32px;
          transition: all 0.2s ease;
          
          &:hover {
            color: #1890ff;
            background-color: #e6f7ff;
          }
          
          &.is-active {
            background-color: #1890ff;
            color: #fff;
            font-weight: 600;
            box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);
            
            &:hover {
              background-color: #40a9ff;
            }
          }
        }
      }
      
      .el-pagination__jump {
        margin-left: 16px;
        color: #606266;
        
        .el-input__wrapper {
          background-color: #f5f7fa;
          border-radius: 4px;
        }
      }
    }
  }
  
  .department-dialog, .member-dialog {
    border-radius: 12px;
    overflow: hidden;
    
    :deep(.el-dialog__header) {
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;
      margin: 0;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    :deep(.el-dialog__body) {
      padding: 24px;
    }
    
    :deep(.el-dialog__footer) {
      padding: 16px 20px;
      border-top: 1px solid #f0f0f0;
    }
    
    :deep(.el-form-item__label) {
      font-weight: 600;
      color: #606266;
    }
    
    .form-input {
      :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
        transition: all 0.3s;
        
        &:hover, &:focus {
          box-shadow: 0 0 0 1px #1890ff inset;
        }
      }
    }
    
    .form-textarea {
      :deep(.el-textarea__inner) {
        border-radius: 8px;
        padding: 10px 12px;
        box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
        transition: all 0.3s;
        
        &:hover, &:focus {
          box-shadow: 0 0 0 1px #1890ff inset;
        }
      }
    }
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      
      .el-button {
        border-radius: 8px;
        padding: 8px 20px;
        font-weight: 500;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
      }
      
      .submit-btn {
        background: linear-gradient(135deg, #1890ff, #36a6ff);
        border-color: #1890ff;
        
        &:hover {
          background: linear-gradient(135deg, #40a9ff, #5cbbff);
          border-color: #40a9ff;
          box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
        }
        
        &:active {
          background: linear-gradient(135deg, #096dd9, #1890ff);
          border-color: #096dd9;
          transform: translateY(0);
        }
      }
    }
  }
  
  .department-info {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    padding: 16px;
    background: #f8faff;
    border-radius: 8px;
    margin-bottom: 20px;
    
    .info-item {
      min-width: 200px;
      
      .label {
        font-weight: 600;
        color: #606266;
        margin-right: 8px;
      }
      
      .value {
        color: #303133;
      }
    }
  }
  
  .member-table {
    margin: 16px 0;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  }
}
</style> 